<?php

namespace App\Http\Middleware;

use Closure;
use Psy\CodeCleaner;

class XSS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $CodeCleaner = new CodeCleaner();
        $userInput = $request->all();
        array_walk_recursive($userInput,function (&$userInput){
            $userInput = strip_tags($userInput);
            $userInput = htmlspecialchars($userInput);
            // $userInput = clean($userInput,true);
        });
        // dd($userInput);
        $request->merge($userInput);
        return $next($request);
    }
    private function clean($str = '', $html = false)
    {
        if (empty($str)) {
            return;
        }
        if (is_array($str)) {
            foreach ($str as $key => $value) {
                $str[$key] = clean($value, $html);
            }
        } else {
            if (get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            if (is_array($html)) {
                $str = strip_tags($str, implode('', $html));
            } elseif (preg_match('|<([a-z]+)>|i', $html)) {
                $str = strip_tags($str, $html);
            } elseif ($html !== true) {
                $str = strip_tags($str);
            }
            $str = trim($str);
            $str = str_replace(".", "", $str);
            $str = str_replace("/", "", $str);
        }
        return $str;
    }
}
